package Kuaishou;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import lombok.extern.slf4j.Slf4j;

/**
 * @author leiwenkang <leiwenkang@kuaishou.com>
 * Created on 2022-01-18
 */
@Slf4j
public class Test49计算60天后的日期 {

    public static final String DEFAULT_SYS_DATE_FMT = "yyyyMMdd";

    public static final long ONE_DAY_TIMESTAMP = 24 * 60 * 60 * 1000;

    public static void main(String[] args) {
        System.out.println(getEstimatedDate("20220706"));
//        System.out.println(getDiffDate(59));
    }

    public static String getDiffDate(int diffDay) {
        return date2str(addDay(new Date(), diffDay));
    }

    public static Date addDay(Date date, int day) {
        if (date == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, day);
        return calendar.getTime();
    }

    /**
     * DATE对象转换成字符日期串
     *
     * @return String
     */
    public static String date2str(Date date) {
        if (date == null) {
            return null;
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_SYS_DATE_FMT);
            return sdf.format(date);
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 获取预估时间（默认60天后）
     * @param date
     * @return
     */
    public static String getEstimatedDate(String date) {
        long dateTime = date2Timestamp(date);
        if (dateTime == 0) {
            return null;
        }
        long futureDateTime = dateTime + ONE_DAY_TIMESTAMP * 60;
        return timestamp2Date(futureDateTime);
    }

    /**
     * eg: 20200402 -> 1585756800000 (毫秒)
     * @param dateStr
     * @return
     * @throws ParseException
     */
    public static long date2Timestamp(String dateStr) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_SYS_DATE_FMT);
            return sdf.parse(dateStr).getTime();
        } catch (ParseException e) {
            log.error("date2Timestamp error msg" + e.getMessage(), e);
        }
        return 0L;
    }
    /**
     * eg: 1585756800000 -> 20200402 00:00
     * @param timestamp
     * @return
     */
    public static String timestamp2Date(long timestamp) {
        SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_SYS_DATE_FMT);
        return sdf.format(new Date(timestamp));
    }

}
